<template>
  <div class="page-container">
    <div class="wrap">
      <header>
        <!-- <div class="weather">
          <img :src="imgSrc">
          <span class="tem">{{ weatcherData.tem }}°C</span>
          <span class="wea">{{ weatcherData.wea }}</span>
        </div> -->
        <h2>"灌助手"果园水肥一体化智能浇灌系统</h2>
        <div class="showTime">
          <span class="time">{{ nowTime }}</span>
          <span class="date">
            <span>{{ week }}</span>
            <span>{{ date }}</span>
          </span>
        </div>
      </header>

      <section class="mainbox">
        <div class="item left">
          <div class="panel">
            <h2>天气</h2>
            <weather />
            <div class="panel-footer"></div>
          </div>
          <div class="panel">
            <h2>当前环境</h2>
            <environment />
            <div class="panel-footer"></div>
          </div>
          <div class="panel">
            <h2>生长方案</h2>
            <growthModel />
            <div class="panel-footer"></div>
          </div>
        </div>

        <!-- 3D模型导入 -->
        <div class="item center">
          <div style="padding: 0;" class="resume">

            <!-- 渲染画布 -->
            <div id="container"></div>

            <!-- 物体信息 -->
            <!-- <div id="clicklabel"
              style="position: absolute;width: 117px; padding: 10px; background: #7bbfea; line-height: 1; border-radius: 5px;opacity: 0.7;">
            </div> -->
            <div id="clicklabel" style="position: absolute; padding: 10px; background: #7bbfea; line-height: 2; border-radius: 5px;opacity: 0.7;">
              <p>地块</p>
              <p>地块温度：</p>
              <p>daa</p>
              <p>SDAs'dsd</p>
              <p>SDAsd</p>
            </div>
          </div>
        </div>

        <div class="item right">
          <div class="panel">
            <h2>灌溉水量/m^3</h2>
            <waterConsumption />
            <div class="panel-footer"></div>
          </div>
          <div class="panel">
            <h2>施肥占比</h2>
            <fertilizer />
            <div class="panel-footer"></div>
          </div>
          <div class="panel">
            <h2>设备信息</h2>
            <!-- <equipment /> -->
            <device />
            <div class="panel-footer"></div>
          </div>
        </div>
      </section>

    </div>

  </div>
</template>

<script>
import "@/assets/js/flexible";
import countTo from "vue-count-to";
import * as THREE from "three";
import { OBJLoader, MTLLoader } from "three-obj-mtl-loader";
const OrbitControls = require("three-orbit-controls")(THREE);

export default {
  name: "page",
  components: {
    countTo,
    THREE,
    OBJLoader,
    MTLLoader,
    OrbitControls,
  },
  props: {},
  data() {
    return {
      nowTime: "",
      week: "",
      date: "",
      timer: null,
      imgSrc: "",
      weatcherData: {},
      startVal: 0,
      geoCoordMap: {},
    };
  },
  computed: {},
  watch: {},
  created() {},
  mounted() {
    // this.getWeather();
    // this.timer = setInterval(() => {
    //   this.getWeather();
    // }, 1000 * 60 * 60);
    this.nowTimes();
    // this.getEchart();
    this.init();
  },
  methods: {
    timeFormate(timeStamp) {
      //显示当前时间
      let newDate = new Date(timeStamp);
      let year = newDate.getFullYear();
      let month =
        newDate.getMonth() + 1 < 10
          ? "0" + (newDate.getMonth() + 1)
          : newDate.getMonth() + 1;
      let date =
        newDate.getDate() < 10 ? "0" + newDate.getDate() : newDate.getDate();
      let hh =
        newDate.getHours() < 10 ? "0" + newDate.getHours() : newDate.getHours();
      let mm =
        newDate.getMinutes() < 10
          ? "0" + newDate.getMinutes()
          : newDate.getMinutes();
      let ss =
        newDate.getSeconds() < 10
          ? "0" + newDate.getSeconds()
          : newDate.getSeconds();
      let week = newDate.getDay();
      let weeks = ["日", "一", "二", "三", "四", "五", "六"];
      let getWeek = "星期" + weeks[week];
      this.week = getWeek;
      this.date = year + "." + month + "." + date;
      this.nowTime = hh + ":" + mm + ":" + ss;
    },
    nowTimes() {
      this.timeFormate(new Date());
      setInterval(this.nowTimes, 1000);
      this.clear();
    },
    clear() {
      clearInterval(this.nowTimes);
      this.nowTimes = null;
    },

    //3D
    init() {
      var scene, camera, renderer, controls, selectObject, x, y;
      scene = initScene();
      //场景自适应
      // window.addEventListener("resize",onWindowResize,false);
      // function onWindowResize(){
      //   camera.aspect = window.innerWidth / window.innerHeight;
      //   camera.updateProjectionMatrix();
      //   renderer.setSize(window.innerWidth,window.innerHeight);
      // }
      function initScene() {
        //相机设置
        var width = 683;
        var height = 806;
        var k = width / height;
        //var s = 300;
        //创建场景
        var scene = new THREE.Scene();
        //创建相机
        //camera = new THREE.PerspectiveCamera(60,window.innerWidth / window.innerHeight,0.01,2200);
        camera = new THREE.PerspectiveCamera(60, k, 0.01, 2200);
        //创建渲染器
        renderer = new THREE.WebGLRenderer({
          antialias: true,
          alpha: true,
          logarithmicDepthBuffer: true,
        });

        //渲染尺寸
        //renderer.setSize(window.innerWidth,window.innerHeight);
        renderer.setSize(width, height);

        renderer.setClearColor(0x000000, 0);
        renderer.setPixelRatio(window.devicePixelRatio);
        document.getElementById("container").appendChild(renderer.domElement);

        //创建坐标轴
        // var axes = new THREE.AxesHelper(100);
        // scene.add(axes);

        camera.position.set(50, 350, 450);
        camera.lookAt(0, 0, 0);
        scene.add(camera);

        //添加环境光源
        const ambientLight = new THREE.AmbientLight(0xcccccc, 1);
        scene.add(ambientLight);
        //添加点光源
        const pointLight = new THREE.PointLight(0xffffff, 0.8);
        camera.add(pointLight);
        //平行光
        const directionalLight = new THREE.DirectionalLight(0xffffff, 0.5);
        directionalLight.position.set(0, 200, 0);
        scene.add(directionalLight);

        //鼠标控件
        controls = new OrbitControls(camera, renderer.domElement);
        controls.addEventListener("change", renderScene);
        controls.enableDamping = true;
        controls.dampingFactor = 0.5;
        //视角最小距离
        controls.minDistance = 200;
        //视角最远距离
        controls.maxDistance = 2000;
        //最大角度
        controls.maxPolarAngle = Math.PI / 2.2;

        //加载3D模型
        var obj_loader = new OBJLoader();
        var mtl_loader = new MTLLoader();
        mtl_loader.load("/state/threejs/garden.mtl", function (materials) {
          console.log(materials);
          obj_loader.setMaterials(materials);
          obj_loader.load("/state/threejs/garden.obj", function (obj) {
            obj.position.set(0, 50, 0);
            scene.add(obj);
            renderScene();
          });
        });

        //鼠标单击触发的方法
        function OnMouseClick(event) {
          let intersects = getIntersects(event);

          //获取选中最近的Mesh对象
          if (
            intersects.length !== 0 &&
            intersects[0].object instanceof THREE.Mesh
          ) {
            console.log("点击对象信息：");
            console.log(intersects[0].object);

            switch (intersects[0].object.name) {
              case "Tree_1":
              case "Tree_2":
              case "Tree_3":
              case "Tree_4":
              case "Tree_5":
              case "Tree_6":
                selectObject = intersects[0].object;
                document.getElementById("clicklabel").style.opacity = 0.7;
                break;
              default:
                console.log("未点击树！");
                document.getElementById("clicklabel").style.opacity = 0;
            }
          } else {
            document.getElementById("clicklabel").style.opacity = 0;
          }
        }

        //获取与射线相交的对象数组
        function getIntersects(event) {
          event.preventDefault();
          x = event.clientX;
          y = event.clientY;
          //console.log('--- 全屏坐标-----');
          // console.log("x:" + event.clientX);
          // console.log("y:" + event.clientY);

          let rayCaster = new THREE.Raycaster();
          let mouse = new THREE.Vector2();
          let getBoundingClientRect = container.getBoundingClientRect();
          mouse.x =
            ((event.clientX - getBoundingClientRect.left) /
              container.offsetWidth) *
              2 -
            1;
          mouse.y =
            -(
              (event.clientY - getBoundingClientRect.top) /
              container.offsetHeight
            ) *
              2 +
            1;

          //console.log('----画布坐标-----');
          // console.log("x:" + mouse.x);
          // console.log("y:" + mouse.y);
          //通过鼠标点击的位置和当前相机的矩阵计算出射线位置
          rayCaster.setFromCamera(mouse, camera);

          //获取与射线相交的对象数组
          let intersects = rayCaster.intersectObjects(scene.children);

          return intersects;
        }

        //改变对象材质属性
        function ChangeMaterial(object) {
          console.log("变材质！");
        }

        function RenderDiv(object) {
          //修改div的位置
          var label = document.getElementById("clicklabel");
          label.style.left = x + "px";
          label.style.top = y + "px";

          //显示模型信息
          //label.innerText = object.name;
          //label.innerText = "——---地块一---——地块温度：26.3°C 地块湿度:622hpaCo2浓度：0.03%光照强度：550lux"
          switch (object.name) {
            case "Tree_1":
              label.childNodes[0].innerText = "———地块1———";
              label.childNodes[1].innerText = "地块温度：25.1°C";
              label.childNodes[2].innerText = "地块湿度：612hpa";
              label.childNodes[3].innerText = "Co2浓度：0.035%";
              label.childNodes[4].innerText = "光照强度：550lux";
              break;
            case "Tree_2":
              label.childNodes[0].innerText = "———地块2———";
              label.childNodes[1].innerText = "地块温度：24.3°C";
              label.childNodes[2].innerText = "地块湿度：592hpa";
              label.childNodes[3].innerText = "Co2浓度：0.029%";
              label.childNodes[4].innerText = "光照强度：523lux";
              break;
            case "Tree_3":
              label.childNodes[0].innerText = "———地块3——";
              label.childNodes[1].innerText = "地块温度：26.3°C";
              label.childNodes[2].innerText = "地块湿度：622hpa";
              label.childNodes[3].innerText = "Co2浓度：0.03%";
              label.childNodes[4].innerText = "光照强度：530lux";
              break;
            case "Tree_4":
              label.childNodes[0].innerText = "———地块4———";
              label.childNodes[1].innerText = "地块温度：27.3°C";
              label.childNodes[2].innerText = "地块湿度：712hpa";
              label.childNodes[3].innerText = "Co2浓度：0.027%";
              label.childNodes[4].innerText = "光照强度：580lux";
              break;
            case "Tree_5":
              label.childNodes[0].innerText = "———地块5———";
              label.childNodes[1].innerText = "地块温度：23.3°C";
              label.childNodes[2].innerText = "地块湿度：679hpa";
              label.childNodes[3].innerText = "Co2浓度：0.025%";
              label.childNodes[4].innerText = "光照强度：650lux";
              break;
            case "Tree_6":
              label.childNodes[0].innerText = "———地块6———";
              label.childNodes[1].innerText = "地块温度：24.3°C";
              label.childNodes[2].innerText = "地块湿度：572hpa";
              label.childNodes[3].innerText = "Co2浓度：0.031%";
              label.childNodes[4].innerText = "光照强度：539lux";
              break;
            default:
              console.log("未点击树！");
              document.getElementById("clicklabel").style.opacity = 0;
          }
        }

        //注册监听事件
        addEventListener("click", OnMouseClick, false);
        //addEventListener('click',RenderDiv,false);
        addEventListener("click", renderScene, false);

        renderScene();
        //控制器，监听鼠标事件
        function renderScene() {
          if (selectObject != undefined && selectObject != null) {
            RenderDiv(selectObject);
          }
          //requestAnimationFrame(renderScene);
          renderer.render(scene, camera);
        }

        return scene;
      }
    },
    animate() {},
    // getWeather() {
    //   // 第三方天气api接口
    //   axios
    //     .get("https://www.tianqiapi.com/api/", {
    //       params: {
    //         appid: "26148275",
    //         appsecret: "2id6H48Y",
    //         version: "v6",
    //       },
    //     })
    //     .then((res) => {
    //       if (res.data) {
    //         if (res.data.wea_img == "xue") {
    //           this.imgSrc = require("../assets/img/brand/xue.png");
    //         } else if (res.data.wea_img == "yin") {
    //           this.imgSrc = require("../assets/img/brand/yin.png");
    //         } else if (
    //           res.data.wea_img == "yu" ||
    //           res.data.wea_img == "bingbao"
    //         ) {
    //           this.imgSrc = require("../assets/img/brand/yu.png");
    //         } else if (res.data.wea_img == "yun") {
    //           this.imgSrc = require("../assets/img/brand/yun.png");
    //         } else if (res.data.wea_img == "wu") {
    //           this.imgSrc = require("../assets/img/brand/wu.png");
    //         } else if (res.data.wea_img == "shachen") {
    //           this.imgSrc = require("../assets/img/brand/shachen.png");
    //         } else if (res.data.wea_img == "lei") {
    //           this.imgSrc = require("../assets/img/brand/lei.png");
    //         } else {
    //           this.imgSrc = require("../assets/img/brand/qing.png");
    //         }
    //         this.weatcherData = res.data;
    //       }
    //     })
    //     .catch((err) => {
    //       console.log(err);
    //     });
    // },
    // convertData(data) {
    //   let res = [];
    //   for (let i = 0; i < data.length; i++) {
    //     let dataItem = data[i];
    //     let fromCoord = this.geoCoordMap[dataItem[0].name];
    //     let toCoord = this.geoCoordMap[dataItem[1].name];
    //     if (fromCoord && toCoord) {
    //       res.push({
    //         fromName: dataItem[0].name,
    //         toName: dataItem[1].name,
    //         coords: [fromCoord, toCoord],
    //         value: dataItem[1].value,
    //       });
    //     }
    //   }
    //   return res;
    // },
    // getEchart() {
    //   let myChart = echarts.init(document.getElementById("chart_map"));

    //   this.geoCoordMap = {
    //
    //   };

    //   let planePath =
    //     "path://M1705.06,1318.313v-89.254l-319.9-221.799l0.073-208.063c0.521-84.662-26.629-121.796-63.961-121.491c-37.332-0.305-64.482,36.829-63.961,121.491l0.073,208.063l-319.9,221.799v89.254l330.343-157.288l12.238,241.308l-134.449,92.931l0.531,42.034l175.125-42.917l175.125,42.917l0.531-42.034l-134.449-92.931l12.238-241.308L1705.06,1318.313z";

    //   let color = ["#fff", "#fff", "#fff"]; //航线的颜色
    //   let series = [];

    //   [
    //
    //   ].forEach((item, i) => {
    //     series.push(
    //       {
    //         name: item[0] + " Top3",
    //         type: "lines",
    //         zlevel: 1,
    //         effect: {
    //           show: true,
    //           period: 6,
    //           trailLength: 0.7,
    //           color: "red", //arrow箭头的颜色
    //           symbolSize: 3,
    //         },
    //         lineStyle: {
    //           normal: {
    //             color: color[i],
    //             width: 0,
    //             curveness: 0.2,
    //           },
    //         },
    //         data: this.convertData(item[1]),
    //       },
    //       {
    //         name: item[0] + " Top3",
    //         type: "lines",
    //         zlevel: 2,
    //         symbol: ["none", "arrow"],
    //         symbolSize: 10,
    //         effect: {
    //           show: true,
    //           period: 6,
    //           trailLength: 0,
    //           symbol: planePath,
    //           symbolSize: 15,
    //         },
    //         lineStyle: {
    //           normal: {
    //             color: color[i],
    //             width: 1,
    //             opacity: 0.6,
    //             curveness: 0.2,
    //           },
    //         },
    //         data: this.convertData(item[1]),
    //       },
    //       {
    //         name: item[0] + " Top3",
    //         type: "effectScatter",
    //         coordinateSystem: "geo",
    //         zlevel: 2,
    //         rippleEffect: {
    //           brushType: "stroke",
    //         },
    //         label: {
    //           normal: {
    //             show: true,
    //             position: "right",
    //             formatter: "{b}",
    //           },
    //         },
    //         symbolSize: (val) => {
    //           return val[2] / 8;
    //         },
    //         itemStyle: {
    //           normal: {
    //             color: color[i],
    //           },
    //           emphasis: {
    //             areaColor: "#2B91B7",
    //           },
    //         },
    //         data: item[1].map((dataItem) => {
    //           return {
    //             name: dataItem[1].name,
    //             value: this.geoCoordMap[dataItem[1].name].concat([
    //               dataItem[1].value,
    //             ]),
    //           };
    //         }),
    //       }
    //     );
    //   });

    //   let option = {
    //     tooltip: {
    //       trigger: "item",
    //       formatter: (params, ticket, callback) => {
    //         if (params.seriesType == "effectScatter") {
    //           return "线路：" + params.data.name + "" + params.data.value[2];
    //         } else if (params.seriesType == "lines") {
    //           return (
    //             params.data.fromName +
    //             ">" +
    //             params.data.toName +
    //             "<br />" +
    //             params.data.value
    //           );
    //         } else {
    //           return params.name;
    //         }
    //       },
    //     },
    //     geo: {
    //       map: "china",
    //       label: {
    //         emphasis: {
    //           show: true,
    //           color: "#fff",
    //         },
    //       },
    //       roam: false,
    //       //   放大
    //       zoom: 1,
    //       itemStyle: {
    //         normal: {
    //           areaColor: "rgba(43, 196, 243, 0.42)",
    //           borderColor: "rgba(43, 196, 243, 1)",
    //           borderWidth: 1,
    //         },
    //         emphasis: {
    //           areaColor: "#2B91B7",
    //         },
    //       },
    // },
    // series: series,
    // };

    //     myChart.setOption(option, true);

    //     window.addEventListener("resize", () => {
    //       myChart.resize();
    //     });
    //   },
    // },
    // beforeDestroy() {
    //   clearInterval(this.timer);
    // },
  },
  beforeCreate() {},
  beforeMount() {},
  beforeUpdate() {},
  updated() {},
  beforeDestroy() {},
  destroyed() {},
  activated() {},
};
</script>

<style lang="scss" scoped>
.page-container {
  position: absolute;
  width: 100%;
  height: 100%;
  background: #000;
  .wrap {
    background: url(../assets/img/bg/bg.jpg) no-repeat #000;
    background-size: cover;
    line-height: 1.15;
    header {
      position: relative;
      height: 1rem;
      background: url(../assets/img/bg/head_bg.png) no-repeat top center;
      background-size: 100% 100%;
      h2 {
        color: #7ef0ff;
        font-size: 0.475rem;
        text-align: center;
        line-height: 0.75rem;
        letter-spacing: 1px;
      }
      // .weather {
      //   position: absolute;
      //   left: 1.375rem;
      //   top: 0.35rem;
      //   font-size: 0.25rem;
      //   color: rgba(126, 240, 255, 0.7);
      //   img {
      //     width: 0.45rem;
      //   }
      //   span {
      //     display: inline-block;
      //   }
      //   .tem {
      //     margin: 0 0.1rem 0 0.2rem;
      //   }
      // }
      .showTime {
        position: absolute;
        // right: 1.375rem;
        right: 3rem;
        top: 0.5rem;
        color: rgba(126, 240, 255, 0.7);
        display: flex;
        .time {
          font-size: 0.28rem;
          margin-right: 0.18rem;
        }
        .date {
          span {
            display: block;
            &:nth-child(1) {
              font-size: 0.12rem;
              text-align: right;
            }
            &:nth-child(2) {
              font-size: 0.14rem;
            }
          }
        }
      }
    }

    .mainbox {
      min-width: 1024px;
      max-width: 1920px;
      padding: 0.125rem 0.125rem 0;
      display: flex;
      .item {
        flex: 3;
        &.center {
          flex: 5;
          margin: 0 0.125rem 0.1rem;
          overflow: hidden;

          .resume {
            background: rgba(101, 132, 226, 0.1);
            padding: 0.1875rem;
            .resume-hd {
              position: relative;
              border: 1px solid rgba(25, 186, 139, 0.17);
              ul {
                display: flex;
                %li-line {
                  content: "";
                  position: absolute;
                  height: 50%;
                  width: 1px;
                  background: rgba(255, 255, 255, 0.2);
                  top: 25%;
                }
                li {
                  position: relative;
                  flex: 1;
                  text-align: center;
                  height: 1.2rem;
                  line-height: 1.2rem;
                  font-size: 0.65rem;
                  color: #ffeb7b;
                  padding: 0.05rem 0;
                  font-family: "DIGITALDREAMFAT";
                  font-weight: bold;
                  &:nth-child(2) {
                    &:after {
                      @extend %li-line;
                      right: 0;
                    }
                    &:before {
                      @extend %li-line;
                      left: 0;
                    }
                  }
                }
              }
              &:before {
                content: "";
                position: absolute;
                width: 30px;
                height: 10px;
                border-top: 2px solid #02a6b5;
                border-left: 2px solid #02a6b5;
                top: 0;
                left: 0;
              }
              &:after {
                content: "";
                position: absolute;
                width: 30px;
                height: 10px;
                border-bottom: 2px solid #02a6b5;
                border-right: 2px solid #02a6b5;
                right: 0;
                bottom: 0;
              }
            }
            .resume-bd {
              ul {
                display: flex;
                li {
                  flex: 1;
                  height: 0.5rem;
                  line-height: 0.5rem;
                  text-align: center;
                  font-size: 0.225rem;
                  color: rgba(255, 255, 255, 0.7);
                  padding-top: 0.125rem;
                }
              }
            }
          }
        }

        .panel {
          position: relative;
          height: 3.875rem;
          border: 1px solid rgba(25, 186, 139, 0.17);
          // background: rgba(255, 255, 255, 0.04)
          //   url(../assets/img/brand/line.png);
          padding: 0 0.1875rem 0;
          margin-bottom: 0.1875rem;
          &:before {
            position: absolute;
            top: 0;
            left: 0;
            content: "";
            width: 10px;
            height: 10px;
            border-top: 2px solid #02a6b5;
            border-left: 2px solid #02a6b5;
          }
          &:after {
            position: absolute;
            top: 0;
            right: 0;
            content: "";
            width: 10px;
            height: 10px;
            border-top: 2px solid #02a6b5;
            border-right: 2px solid #02a6b5;
          }

          .panel-footer {
            position: absolute;
            left: 0;
            bottom: 0;
            width: 100%;
            &:before {
              position: absolute;
              bottom: 0;
              left: 0;
              content: "";
              width: 10px;
              height: 10px;
              border-bottom: 2px solid #02a6b5;
              border-left: 2px solid #02a6b5;
            }
            &:after {
              position: absolute;
              bottom: 0;
              right: 0;
              content: "";
              width: 10px;
              height: 10px;
              border-bottom: 2px solid #02a6b5;
              border-right: 2px solid #02a6b5;
            }
          }

          h2 {
            height: 0.6rem;
            line-height: 0.6rem;
            text-align: center;
            color: #fff;
            font-size: 0.225rem;
            font-weight: 400;
            a {
              margin: 0 0.1875rem;
              color: #fff;
              text-decoration: none;
            }
          }
          .chart {
            height: 3rem;
          }
        }
      }
    }
  }
}

@-webkit-keyframes rotate {
  from {
    transform: translate(-50%, -50%) rotate(0deg);
  }
  to {
    transform: translate(-50%, -50%) rotate(360deg);
  }
}
@keyframes rotate {
  from {
    transform: translate(-50%, -50%) rotate(0deg);
  }
  to {
    transform: translate(-50%, -50%) rotate(360deg);
  }
}

@-webkit-keyframes rotate1 {
  from {
    transform: translate(-50%, -50%) rotate(0deg);
  }
  to {
    transform: translate(-50%, -50%) rotate(-360deg);
  }
}
@keyframes rotate1 {
  from {
    transform: translate(-50%, -50%) rotate(0deg);
  }
  to {
    transform: translate(-50%, -50%) rotate(-360deg);
  }
}

@media screen and (max-width: 1024px) {
  html {
    font-size: 42px !important;
  }
}
@media screen and (min-width: 1920) {
  html {
    font-size: 80px !important;
  }
}
</style>
